package com.pdf;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.pdmodel.PDDocument;

import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/**
 * @Classname PdfDemo
 * @Description 合并PDF
 * @Date 2023/8/31 23:28
 * @Created by 86182
 */
public class PdfDemo {
    public static void main(String[] args) throws IOException {
        String pdfPath = "D:\\testpdf\\";

        String newPdf = "刘晓斌_{}.pdf";
        String newPdfFilePath = "D:\\newpdf\\";
        List<File> fileList = FileUtil.loopFiles(pdfPath);
        int pdfNum = fileList.size();
        //PDF集合
        List<PDDocument> pdDocumentList = new LinkedList<>();

        //PDF文件流集合
        List<File> files = new LinkedList<>();
        //将所有需要合并的PDF读取出来
        for (int i = 1; i <= pdfNum; i++) {
            File file = new File(pdfPath + StrUtil.format(newPdf, i));
            files.add(file);
            PDDocument loadPDF = PDDocument.load(file);
            pdDocumentList.add(loadPDF);

        }
        PDFMergerUtility merge = new PDFMergerUtility();
        merge.setDestinationFileName(newPdfFilePath + StrUtil.format(newPdf, "_最终合并版"));
        for (File file : files) {
            merge.addSource(file);
        }
        merge.mergeDocuments(null);

        System.out.println("合并success");
        for (PDDocument pdDocument : pdDocumentList) {
            pdDocument.close();
        }

    }

}
